package com.hzcx.app.simplechat.ui.chat;

import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.ui.chat.adapter.GdMapPoiAdapter;
import com.hzcx.app.simplechat.ui.chat.bean.GdMapPoiBean;
import com.hzcx.app.simplechat.ui.chat.event.ChatLocationEvent;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.map.AMapUtils;
import com.hzcx.app.simplechat.util.map.GdMapUtils;
import com.hzcx.app.simplechat.util.map.LngLat;
import com.wang.avi.AVLoadingIndicatorView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 聊天界面-选取位置
 */
public class ChatLocationActivity extends BaseActivity {

    @BindView(R.id.iv_top)
    ImageView ivTop;
    @BindView(R.id.map_view)
    MapView mapView;
    @BindView(R.id.btn_send)
    Button btnSend;
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.iv_bottom)
    ImageView ivBottom;
    @BindView(R.id.rv_poi)
    RecyclerView rvPoi;
    @BindView(R.id.loading_view)
    AVLoadingIndicatorView loadingView;
    private AMap aMap;
    private UiSettings uiSettings;
    private MyLocationStyle myLocationStyle;
    private Marker marker;
    private String locationCity = "";
    private boolean isLocationSuccess = false;
    private GdMapPoiAdapter poiAdapter;
    private List<GdMapPoiBean> poiData;
    private double mineLat;
    private double mineLng;

    @Override
    public int getLayout() {
        return R.layout.activity_chat_location;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        changeStatusBarTextColor(false);
        loadingView.setIndicatorColor(getResources().getColor(R.color.color_A6A8B0));

        poiData = new ArrayList<>();
        poiAdapter = new GdMapPoiAdapter(poiData);
        rvPoi.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvPoi.setAdapter(poiAdapter);
    }

    @Override
    public void initData() {

        poiAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                poiAdapter.setPos(position);
            }
        });

    }

    @OnClick({R.id.btn_send})
    public void viewOnClick(View view){
        switch (view.getId()){
            case R.id.btn_send: // 发送
                sendLocation();
                break;
        }
    }

    /**
     *  发送位置
     */
    private void sendLocation(){
        if(poiAdapter.getPos()==-1){
            showError("请选择要发送的地址");
            return;
        }
        EventBus.getDefault().post(new ChatLocationEvent(poiData.get(poiAdapter.getPos())));
        finish();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapView.onCreate(savedInstanceState);
        //初始化地图控制器对象
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        initMap();
    }

    /**
     * 设置地图UI相关参数
     */
    private void initMap() {
        uiSettings = aMap.getUiSettings();
        uiSettings.setZoomControlsEnabled(false); // 隐藏缩放按钮


        // 获取地图蓝点
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//定位一次，且将视角移动到地图中心点。
        myLocationStyle.showMyLocation(false);
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
                isLocationSuccess = true;
                mineLat = location.getLatitude();
                mineLng = location.getLongitude();
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 14));
                addMark(location.getLatitude(), location.getLongitude());
                searchByPoi(location.getLatitude(), location.getLongitude(), locationCity);
            }
        });

        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
                if (!isLocationSuccess) {
                    return;
                }
                addMark(cameraPosition.target.latitude, cameraPosition.target.longitude);
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                if (!isLocationSuccess) {
                    return;
                }
                searchByPoi(cameraPosition.target.latitude, cameraPosition.target.longitude, locationCity);
            }
        });
    }

    /**
     * 添加地图mark
     */
    private void addMark(double lat, double lng) {
        if (marker == null) {
            marker = aMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng))
                    .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_icon_chat_location_marker)))
                    .draggable(true));
        } else {
            marker.setPosition(new LatLng(lat, lng));
        }
    }

    /**
     * 搜索poi地址
     *
     * @param lat
     * @param lng
     * @param city
     */
    private void searchByPoi(double lat, double lng, String city) {
        loadingView.setVisibility(View.VISIBLE);
        poiData.clear();
        poiAdapter.notifyDataSetChanged();
        GdMapUtils.getInstance().getAddressList(lat, lng, new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int i) {
                if (i == 1000) {
                    if (poiResult != null && poiResult.getQuery() != null) {
                        if (poiResult.getQuery().equals(GdMapUtils.getInstance().getQuery())) {
                            for (PoiItem item : poiResult.getPois()) {
                                GdMapPoiBean bean = new GdMapPoiBean();
                                bean.setLat(item.getLatLonPoint().getLatitude());
                                bean.setLng(item.getLatLonPoint().getLongitude());
                                bean.setTitle(item.getTitle());
                                bean.setAddress(item.getAdName() + item.getSnippet());
                                LogUtils.d("mineLng:"+mineLng+"    mineLat:"+mineLat+"    lng:"+bean.getLng()+"    lat:"+bean.getLat());
                                bean.setDistance(AMapUtils.calculateLineDistanceToStr(new LngLat(mineLng, mineLat),
                                        new LngLat(bean.getLng(), bean.getLat())));
                                poiData.add(bean);
                            }
                            loadingView.setVisibility(View.GONE);
                            poiAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mapView.onDestroy();
        GdMapUtils.getInstance().stopLocation();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mapView.onSaveInstanceState(outState);
    }

}
